<script setup lang="ts">

import {AuthApi, CaptchaApi, type LoginRO, UserApi} from '@/api'
import {authService} from '@/service/AuthService'

const form = ref<LoginRO>({
  username: '',
  password: '',
  captcha: {
    id: '',
    value: ''
  }
})

const router = useRouter()
const captchaImg = ref<string>()
const captchaApi = new CaptchaApi()
const errorMsg = ref<string>()
const needCatpcha = ref(false)

function loadCaptcha(){
  captchaApi.getCaptcha().then((response) => {
    captchaImg.value = response.data.imageBase64
    form.value.captcha!.id = response.data.id
  })
}

function login() {
  authService.login(form.value).then((response) => {
    errorMsg.value = ""
    router.push('/')
  }).catch((err)=>{
    let errData = err.response.data
    if(errData.type == "LOGIN_CAPTCHA_ERROR"){
      needCatpcha.value = true
    }
    if (needCatpcha.value) {
      loadCaptcha()
    }
    errorMsg.value = errData.message
  })
}

</script>

<template>
  <!--use element-plus-->
  <div class="h-full bg-sky-9 flex items-center justify-center">
    <div class="w-25em bg-white rounded p-8 shadow-2xl">
      <div class="text-center text-2xl font-bold">Login</div>
      <div class="pt-4">
        <ElForm :model="form" label-width="4em">
          <ElFormItem label="用户名">
            <ElInput v-model="form.username" placeholder="用户名" />
          </ElFormItem>
          <ElFormItem label="密码">
            <ElInput v-model="form.password" placeholder="密码" />
          </ElFormItem>
          <ElFormItem label="验证码" v-if="needCatpcha">
            <ElRow>
              <ElCol :span="10">
                <ElInput v-model="form.captcha!.value" placeholder="Captcha" />
              </ElCol>
              <ElCol :span="8" :offset="1">
                <img :src=captchaImg alt="captcha" class="w-100px h-30px" @click="loadCaptcha()"/>
              </ElCol>
            </ElRow>
          </ElFormItem>
          <ElFormItem v-if="errorMsg" label="">
            <div class="text-red-500">{{errorMsg}}</div>
          </ElFormItem>
          <ElFormItem>
            <ElButton type="primary" @click="login" class="w-full">Login</ElButton>
          </ElFormItem>
        </ElForm>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>
